// 获取输入框节点
let input_box = document.querySelector(".input_area input");
// 获取输入区节点
let input_area_box = document.querySelector(".input_area");
// 获取搜索区节点
let select_area_box = document.querySelector(".select_area");
// 获取主要区域节点
let main_box = $("main");
// 获取删除按钮节点
let del_logo_box = $(".del_btn");

// ------------------- ↓ 文本框聚焦失焦 ↓ ----------------------------↓
input_box.addEventListener("focus", () => {
  input_area_box.classList.add("blue_border");
  if (input_box.value.trim()) render(input_box.value);
});

input_box.addEventListener("blur", () => {
  input_area_box.classList.remove("blue_border");

  reset();
});
// ------------------- ↑ 文本框聚焦失焦 ↑ ----------------------------↑

// ------------------- ↓ 文本框输入 ↓ ----------------------------↓
input_box.addEventListener("input", (evt) => {
  if (input_box.value.trim()) {
    render(input_box.value);
  } else {
    reset();
  }

  if (input_box.value) {
    // del_logo_box.classList.add("");
    del_logo_box.addClass("visible_btn");
  } else {
    del_logo_box.removeClass("visible_btn");
  }
});

input_box.addEventListener("keydown", () => {
  if (input_box.value == "") reset();
});
// ------------------- ↑ 文本框输入 ↑ ----------------------------↑

// ------------------- ↓ 清空文本 ↓ ----------------------------↓
del_logo_box.bind("click",()=>{
  input_box.value = "";
  reset();
})

// ------------------- ↑ 清空文本 ↑ ----------------------------↑


function render(select_target) {
  input_area_box.classList.add("ia_show");
  select_area_box.classList.add("sa_show");

  //jsonp获取数据(并且插入节点)
  let tem_script = document.createElement("script");
  tem_script.src = `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=38516,36559,38529,38469,38468,37709,26350,38568,38186,38543&wd=${select_target}&req=2&csor=2&pwd=1&cb=getNodeList&_=1683544836778`;
  document.body.appendChild(tem_script);

  tem_script.onload = function () {
    tem_script.remove();
  };
}

// 删节点
function reset() {
  input_area_box.classList.remove("ia_show");
  select_area_box.classList.remove("sa_show");

  let tmp = $(".result_area");
  tmp.remove();
}

// 生成节点
function getNodeList(obj) {
  if (obj.g) {
    let node_str = "";
    obj.g.forEach((item) => {
      node_str += `<div class="result_item">${item.q}</div>`;
    });

    let tmp = $(".result_item");
    let flag = $(".feedback_line");
    if (flag.length == 0) {
      let new_section = $(`<section class="result_area">
    <hr>
    ${node_str}
    <div class="feedback_line">
      <span>反馈</span>
    </div>
   </section> `);

      main_box.append(new_section);
    } else {
      for (let i = 0; i < tmp.length; i++) {
        tmp[i].remove();
      }

      flag.before($(node_str));
    }
  } else if ($(".feedback_line").length == 0) {
    let new_section = $(`<section class="result_area">
    <hr>
    <div class="feedback_line">
      <span>反馈</span>
    </div>
   </section> `);

    main_box.append(new_section);
  }
}
